package com.gensdai.leliang.activity;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.classic.common.MultipleStatusView;
import com.gensdai.leliang.AppApplication;
import com.gensdai.leliang.BuildConfig;
import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivity;
import com.gensdai.leliang.common.adapter.HotProductYouLikeAdapterRec;
import com.gensdai.leliang.common.clickinterface.OnProductClickListener;
import com.gensdai.leliang.entity.parseBean.ProductInfo;
import com.gensdai.leliang.remoteInterface.RetrofitFactory;
import com.gensdai.leliang.retrofitUtils.BaseObserverList;
import com.gensdai.leliang.retrofitUtils.ModelFilteredFactory;
import com.gensdai.leliang.retrofitUtils.exception.APIException;
import com.gensdai.leliang.utils.BaseUtils;
import com.gensdai.leliang.utils.PreferencesUtils;
import com.gensdai.leliang.view.Toaster;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import retrofit2.HttpException;

/**
 * 收藏列表
 * Created by zsxx on 2017/8/17.
 */

public class ActivityCollctionList extends BaseActivity {
    @BindView(R.id.collection_list_rec)
    RecyclerView collection_list_rec;

    @BindView(R.id.collctionMultiplestatusview)
    MultipleStatusView collctionMultiplestatusview;

    @Override
    protected String getTitleStr() {
        return "我的收藏";
    }

    @Override
    protected boolean isShowBackButton() {
        return true;
    }

    @Override
    protected boolean isCustomTitle() {
        return false;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_collection_list;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initRecyclerView(collection_list_rec);


    }

    @Override
    protected void onResume() {
        super.onResume();
        getCommentList();
    }

    private void getCommentList() {

        if (!BaseUtils.isNetworkAvailable(this)) {
            //没有网络显示无网络
            collctionMultiplestatusview.showNoNetwork();
            return;
        }

        String uno = PreferencesUtils.getStringPreference(this, OrderPreper2Activity.prefreceName, "userno", "");
        if (TextUtils.isEmpty(uno)) {
            if (BuildConfig.DEBUG) {
                Toaster.showOneToast("没有userno");
                return;
            }
        }
        Map<String, String> params = new HashMap<>();
        params.put("userNo", uno);
        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().COLLCTIONlIST(params))
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
                        Log.d("accept", "accept");
                        collctionMultiplestatusview.showLoading();
                    }
                })
                .subscribe(new BaseObserverList<ProductInfo>(this) {
                    @Override
                    public void onRequestEnd() {
                        super.onRequestEnd();
                    }

                    @Override
                    public void onHandleSuccess(List<ProductInfo> t) {
                        attrRecycler(t);
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        collctionMultiplestatusview.post(new Runnable() {
                            @Override
                            public void run() {
                                collctionMultiplestatusview.showError();
                            }
                        });
                    }

                    @Override
                    public void onFailure(final Throwable e) {
                        super.onFailure(e);
                        collctionMultiplestatusview.post(new Runnable() {
                            @Override
                            public void run() {
                                if (e instanceof APIException) {
                                    APIException exception = (APIException) e;
                                    Toast.makeText(AppApplication.getContext(), exception.message, Toast.LENGTH_SHORT).show();
                                } else if (e instanceof UnknownHostException) {
                                    Toast.makeText(AppApplication.getContext(), "请打开网络", Toast.LENGTH_SHORT).show();
                                } else if (e instanceof SocketTimeoutException) {
                                    Toast.makeText(AppApplication.getContext(), "请求超时", Toast.LENGTH_SHORT).show();
                                } else if (e instanceof ConnectException) {
                                    Toast.makeText(AppApplication.getContext(), "连接失败", Toast.LENGTH_SHORT).show();
                                } else if (e instanceof HttpException) {
                                    Toast.makeText(AppApplication.getContext(), "请求异常" + ((HttpException) e).code(), Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(AppApplication.getContext(), "请求失败", Toast.LENGTH_SHORT).show();
                                }
                                collctionMultiplestatusview.showError();
                            }
                        });
                    }
                });

    }

    private void attrRecycler(List<ProductInfo> t) {

        if (t != null && t.size() > 0) {
            GridLayoutHelper layoutHelper = new GridLayoutHelper(2);
            layoutHelper.setPadding(getResources().getDimensionPixelOffset(R.dimen.px30dp), 0, getResources().getDimensionPixelOffset(R.dimen.px30dp), 0);
            layoutHelper.setBgColor(ContextCompat.getColor(this, R.color.bgColor_new));
            layoutHelper.setAutoExpand(false);
            //横间距
            layoutHelper.setHGap(getResources().getDimensionPixelOffset(R.dimen.px10dp));
            layoutHelper.setVGap(getResources().getDimensionPixelOffset(R.dimen.px10dp));
            if (adapters != null) {
                adapters.clear();
                HotProductYouLikeAdapterRec menuAdapter = new HotProductYouLikeAdapterRec(this, layoutHelper, t);
                menuAdapter.setOnProductClicklistener(productClickListener);
                adapters.add(menuAdapter);
            }
            //初始化完毕后开始适配

            delegateAdapter.setAdapters(adapters);
            collection_list_rec.setAdapter(delegateAdapter);

            //延迟3秒后显示内容页面
            collctionMultiplestatusview.postDelayed(new Runnable() {
                @Override
                public void run() {
                    collctionMultiplestatusview.showContent();
                }
            }, 500);
        } else {
            //延迟3秒后显示内容页面
            collctionMultiplestatusview.postDelayed(new Runnable() {
                @Override
                public void run() {
                    collctionMultiplestatusview.showEmpty();
                }
            }, 500);
        }
    }


    OnProductClickListener productClickListener = new OnProductClickListener<ProductInfo>() {
        @Override
        public void OnProductClick(ProductInfo info, int position) {
            startPorductInfo(info.getId());
        }
    };

    //跳转到产品详情页面
    private void startPorductInfo(String pid) {
        Intent it = new Intent(this, ProductDetail.class);
        it.putExtra(ProductDetail.EXTRA_PID, pid/*"0063ed7e81b64fec8e0aa88212987639"*/);
        startActivity(it);
    }


    DelegateAdapter delegateAdapter;
    List<DelegateAdapter.Adapter> adapters;

    private void initRecyclerView(RecyclerView recyclerView) {
        //创建线性布局
        final VirtualLayoutManager layoutManager = new VirtualLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        // layoutManager.setReverseLayout(true);

        RecyclerView.ItemDecoration itemDecoration = new RecyclerView.ItemDecoration() {
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position = ((VirtualLayoutManager.LayoutParams) view.getLayoutParams()).getViewPosition();
                outRect.set(4, 4, 4, 4);
            }
        };

        final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();

        recyclerView.setRecycledViewPool(viewPool);

        // recyclerView.addItemDecoration(itemDecoration);
        viewPool.setMaxRecycledViews(0, 20);

        delegateAdapter = new DelegateAdapter(layoutManager, false);

        recyclerView.setAdapter(delegateAdapter);

        adapters = new LinkedList<>();
    }
}
